package com.hellprototypes.hellwatch.assistant;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class IR_RemoteLearning extends Activity {
    private final static String TAG = "HellWatch-IR_RemoteLearning";
    public static final int RadioButton_IDS[] = {
        R.id.rb_0,R.id.rb_1,R.id.rb_2,R.id.rb_3,R.id.rb_4,
        R.id.rb_5,R.id.rb_6,R.id.rb_7,R.id.rb_8,R.id.rb_9,
        R.id.rb_back,R.id.rb_ch_down,R.id.rb_ch_up,R.id.rb_exit,
        R.id.rb_menu,R.id.rb_mute,R.id.rb_ok,R.id.rb_pwr_off1,
        R.id.rb_pwr_off2,R.id.rb_vol_down,R.id.rb_vol_up,
    };
    public RadioButton [] mRadioButtons;
    public IR_LearnReceiver mIR_LearnReceiver;
    public TextView mTextView;
    public EditText mCfgFileName;
    public Map mRB_irKey_Map;

    public List mIR_CodeList;
    public class IR_Code {
        public int KEY_index;
        public byte [] IR_Code;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ir_remote_learning);

        //Log.d(TAG, "# onCreate() len=" + RadioButton_IDS.length);
        mRB_irKey_Map = new HashMap();
        mRadioButtons = new RadioButton[RadioButton_IDS.length];
        for(int i=0; i<RadioButton_IDS.length; i++) {
            mRadioButtons[i] = (RadioButton)findViewById(RadioButton_IDS[i]);
            mRB_irKey_Map.put(mRadioButtons[i], Integer.valueOf(Common.IR_KEY_INDEX_LIST[i]));
        }
        mTextView = (TextView)findViewById(R.id.tv_ir_code);
        mCfgFileName = (EditText)findViewById(R.id.etIR_cfg_file_name);

        mIR_CodeList = new ArrayList();
        Log.d(TAG, "# onCreate()");
    }

    @Override
    public void onStart() {
        mIR_LearnReceiver = new IR_LearnReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Common.HWIR_ACTION);
        registerReceiver(mIR_LearnReceiver, filter);

        Log.d(TAG, "# onStart()");
        super.onStart();
    }

    @Override
    protected void onStop() {
        Log.d(TAG, "# onStop()");
        unregisterReceiver(mIR_LearnReceiver);
        super.onStop();
    }

    public void on_save_IR_code_cfg_click(View view)
    {
        if(mIR_CodeList.size() == 0) {
            Toast.makeText(getApplicationContext(),"没有数据需要保存", Toast.LENGTH_SHORT).show();
            return;
        }
        String fileName = mCfgFileName.getText().toString();
        if(fileName.isEmpty()) {
            Toast.makeText(getApplicationContext(),"请先输入文件名", Toast.LENGTH_SHORT).show();
            return;
        }
        fileName += ".ir";

        byte [] ir_codes = new byte[mIR_CodeList.size() * 7];
        int index = 0;

        for(int i=0; i<mIR_CodeList.size(); i++) {
            IR_Code ir = new IR_Code();
            ir = (IR_Code)mIR_CodeList.get(i);
            //Log.d(TAG, "on_save_IR_code_cfg_click key : "+ ir.KEY_index);
            byte [] irc = ir.IR_Code;
            if(irc.length == 6) {
                ir_codes[index++] = (byte) ir.KEY_index;
                for (int j = 0; j < 6; j++) {
                    ir_codes[index++] = irc[j];
                }
            }
        }
        try {
            saveIrCodeToFile(fileName, ir_codes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void on_load_IR_code_cfg_click(View view)
    {
        String path = Environment.getExternalStorageDirectory().toString() + "/HellWatch";
        File dir = new File(path);
        File file[] = dir.listFiles();
        //Log.d(TAG, "Size: "+ file.length);
        int items = file.length;
        if(items == 0) {
            Toast.makeText(getApplicationContext(),"没有找到文件", Toast.LENGTH_SHORT).show();
            return;
        }
        List<String> ir_fileName_list = new ArrayList<String>();
        for (int i=0; i < items; i++) {
            String fileName = file[i].getName();
            if((fileName.length() > 3) && fileName.endsWith(".ir")) {
                ir_fileName_list.add(fileName);
            }
        }
        if(ir_fileName_list.size() == 0) {
            Toast.makeText(getApplicationContext(),"没有找到红外数据文件", Toast.LENGTH_SHORT).show();
            return;
        }
        //final  String [] IR_FileList = new String[ir_fileName_list.size()];
        final String[] IR_FileList = ir_fileName_list.toArray(new String[ir_fileName_list.size()]);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("请选择一个文件");
        builder.setItems(IR_FileList, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                Toast.makeText(getApplicationContext(), IR_FileList[item], Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(Common.HWIR_ACTION);
                intent.putExtra(Common.BUNDLE_KEY_IR_FLOAD, IR_FileList[item]);
                sendBroadcast(intent);
            }
        });
        builder.create().show();
    }

    public void saveIrCodeToFile(String fileName, byte[] bytes) throws IOException {
        String filePath = Environment.getExternalStorageDirectory().toString() + "/HellWatch";
        //Log.d(TAG, "# filePath 1= " + filePath);
        File dir = new File(filePath);
        if (!dir.exists()){
            if (!dir.mkdir()){
                Toast.makeText(getApplicationContext(),"无法创建目录", Toast.LENGTH_SHORT).show();
                return;
            }
        }
        filePath += "/" + fileName;
        //Log.d(TAG, "# filePath 2= " + filePath);

        File file = new File(filePath);
        if(file.exists()) {
            Toast.makeText(getApplicationContext(),"文件已经存在，请更换文件名", Toast.LENGTH_LONG).show();
            return;
        }

        Log.d(TAG, "# Save File Data = " + Common.byte2hex(bytes));
        BufferedOutputStream bos = null;
        FileOutputStream fos=null;
        try {
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        }finally {
            if(bos != null) {
                try  {
                    bos.flush();
                    bos.close();
                    fos.close();
                    Toast.makeText(getApplicationContext(),"文件保存成功", Toast.LENGTH_SHORT).show();
                } catch(Exception e){}
            }
        }
    }

    public void loadIrCodeFromFile(String filePath) throws IOException {
        File file = new File(filePath);
        if(!file.exists()) {
            Toast.makeText(getApplicationContext(),"文件不存在", Toast.LENGTH_LONG).show();
            return;
        }
        InputStream is = new FileInputStream(file);
        long length = file.length();

        if (length < 7) {
            is.close();
            return;
         }
        byte[] IrDataBytes = new byte[(int)length];
        int offset = 0;
        int numRead = 0;
        while (offset < IrDataBytes.length && (numRead=is.read(IrDataBytes, offset, IrDataBytes.length-offset)) >= 0) {
            offset += numRead;
        }
        is.close();

        Log.d(TAG, "# Load File Data = " + Common.byte2hex(IrDataBytes));
        //=================================
        mIR_CodeList.clear();
        int index =0;
        while(index < IrDataBytes.length) {
            IR_Code ir = new IR_Code();
            byte [] byte6 = new byte[6];
            ir.KEY_index = (int)IrDataBytes[index++];
            for(int i=0; i<6; i++) {
                byte6[i] = IrDataBytes[index++];
            }
            ir.IR_Code = byte6;
            mIR_CodeList.add(ir);
        }
        //Log.d(TAG, "list size: "+ mIR_CodeList.size());
        //set color flasg
        for(int i=0; i<mIR_CodeList.size(); i++) {
            IR_Code iir = (IR_Code)mIR_CodeList.get(i);
            int key_index = iir.KEY_index;
            for(int j=0; j<mRadioButtons.length; j++) {
                if(mRB_irKey_Map.containsKey(mRadioButtons[j])) {
                    if(key_index == ((Integer) mRB_irKey_Map.get(mRadioButtons[j])).intValue()) {
                        mRadioButtons[j].setTextColor(Color.rgb(0, 0, 255));
                    }
                }
                //Log.d(TAG, "i= "+ i + " j=" + j);
            }
        }
    }

    public class IR_LearnReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //Log.d(TAG, "# IR_LearnReceiver onReceive");
            String action = intent.getAction();
            if(action.equals(Common.HWIR_ACTION)) {
                Bundle bundle = intent.getExtras();
                if(bundle.containsKey(Common.BUNDLE_KEY_IR_DATA)) {
                    byte [] ir_code = bundle.getByteArray(Common.BUNDLE_KEY_IR_DATA);
                    //Log.d(TAG, "IR decode data received:" + Common.byte2hex(ir_code));
                    mTextView.setText(Common.byte2hex(ir_code));
                    Save_IR_Code(ir_code);
                } else
                if(bundle.containsKey(Common.BUNDLE_KEY_IR_FLOAD)) {
                    String fileName = bundle.getString(Common.BUNDLE_KEY_IR_FLOAD);
                    Log.d(TAG, "# load filePath= " + fileName);
                    if(!fileName.endsWith(".ir")) {
                        Toast.makeText(getApplicationContext(),"不是红外数据文件", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    String filePath = Environment.getExternalStorageDirectory().toString() + "/HellWatch/" + fileName;
                    try {
                        loadIrCodeFromFile(filePath);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public void Save_IR_Code(byte [] ir_code)
    {
        RadioButton selected_rb = null;
        for(int i=0; i<mRadioButtons.length; i++) {
            if(mRadioButtons[i].isChecked()) {
                selected_rb = mRadioButtons[i];
            }
        }
        int ir_key_index = -1;
        if(selected_rb != null) {
            if(mRB_irKey_Map.containsKey(selected_rb)) {
                ir_key_index = ((Integer)mRB_irKey_Map.get(selected_rb)).intValue();
            } else {
                Toast.makeText(getApplicationContext(),"未找到索引键值", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(getApplicationContext(),"需要选择一个目标项", Toast.LENGTH_SHORT).show();
        }
        if((ir_key_index >= 0) && (ir_code.length == 6)) {
            for(int i=0; i<mIR_CodeList.size(); i++) {
                IR_Code ir = (IR_Code)mIR_CodeList.get(i);
                //Log.d(TAG, "# ir.KEY_index ="+ ir.KEY_index + " ir_key_index =" + ir_key_index);
                if(ir.KEY_index == ir_key_index) {
                    mIR_CodeList.remove(i);
                }
            }
            IR_Code ir_c = new IR_Code();
            ir_c.KEY_index = ir_key_index;
            ir_c.IR_Code = ir_code;
            mIR_CodeList.add(ir_c);
            //Log.d(TAG, "Save_IR_Code key : "+ ir_key_index);
            //Log.d(TAG, "mIR_CodeList size : "+ mIR_CodeList.size());

            selected_rb.setTextColor(Color.rgb(255, 0, 0));
            Toast.makeText(getApplicationContext(),"键值：" + ir_key_index + " 已处理", Toast.LENGTH_SHORT).show();
        }
    }

    public void onRadioButtonClick(View view) {
        //Log.d(TAG, "# onRadioButtonClick()");
        RadioButton curr_rb = (RadioButton)view;
        for(int i=0; i<mRadioButtons.length; i++) {
            if(mRadioButtons[i] != curr_rb) {
                mRadioButtons[i].setChecked(false);
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.ir_remote_learning, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
